package sw6.launcher;

import girafPlace.lib.Application;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.List;

import sw6.launcher.TableInfo.Applications;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

/**
 * Sets up the adapter for maintaining the list of SSIDs to be blacklisted for applications.
 * @author sw6c
 *
 */
public class ApplicationsSSIDAdapter extends BaseAdapter {
	private Context mContext;
	private List<Uri> uris = new ArrayList<Uri>();
	private String tag = "GIRAF";

	/** Constructs a new ApplicationsSSIDAdapter in the given context */
	public ApplicationsSSIDAdapter(Context context) {
		mContext = context;
		String[] projection = {Applications._ID};
		Cursor cursor = mContext.getContentResolver().query(ApplicationInfoProvider.CONTENT_URI, projection, null, null, null);
		
		this.notifyDataSetInvalidated();
		if(cursor.moveToFirst()) {
			do{
				int id = cursor.getInt(cursor.getColumnIndex(Applications._ID));
				
				Uri uri = Uri.withAppendedPath(ApplicationInfoProvider.CONTENT_URI, Integer.toString(id));
				
				uris.add(uri);
				
			}while(cursor.moveToNext());
		}
		cursor.close();
		this.notifyDataSetChanged();
	}
	
	
	@Override
	public int getCount() {
		return uris.size();
	}

	@Override
	public Object getItem(int position) {
		return uris.get(position);
	}

	@Override
	public long getItemId(int position) {
		return Integer.parseInt(uris.get(position).getLastPathSegment());
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
	  	TextView textView;
    	if (convertView == null) {  // if it's not recycled, initialize some attributes
    		textView = new TextView(parent.getContext());        
    	} else {
    		textView = (TextView) convertView;
    	}
    	textView.setTextSize(20);
    	
    	Cursor cursor = mContext.getContentResolver().query(uris.get(position), null, null, null, null);
    	
    	cursor.moveToFirst();
    	Application app;
    	ByteArrayInputStream bis = new ByteArrayInputStream (cursor.getBlob(cursor.getColumnIndex(Applications.APPLICATION_OBJECT)));
	    ObjectInputStream ois;
		try {
			ois = new ObjectInputStream (bis);
			app = (Application) ois.readObject();
			textView.setText(app.getName());
		} catch (StreamCorruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			Log.e(tag ,"The application class could not be found");
		}
    	cursor.close();
    	
    	return textView;
	}

}
